package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.enums.ParamEnum;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed=null;
        //整个有异常 try catch
        try {
            long startTime = System.currentTimeMillis();

             proceed = pjp.proceed();

             long endTime = System.currentTimeMillis();
            Object[] args = pjp.getArgs();
            String param = JSONUtil.toJsonStr(args);
            String returnValue = JSONUtil.toJsonStr(proceed);

            OperateLog operateLog = OperateLog.builder()
                    .operateUserId(CurrentUserContextHolders.get())
                    .operateTime(LocalDateTime.now())
                    .className(pjp.getTarget().getClass().getName())
                    .methodName(pjp.getSignature().getName())
                    .methodParams(param)
                    .returnValue(returnValue)
                    .costTime(endTime - startTime)
                    .build();
            //插入数据库异常不耽误整个流程 所以try catch
            try {
             this.operateLogMapper.insert(operateLog);
            }catch (Exception e){
                log.error("操作日志插入失败:{}", e.getMessage());
            }

        }catch (Exception e){
            proceed= Result.error(ParamEnum.OPERATION_FAIL.getMsg());
            log.error("操作失败:{}", e.getMessage());
        }
        return proceed;
    }
}
